

import java.util.PriorityQueue;

class MyTimeTask implements Comparable<MyTimeTask> {
    private Runnable runnable;
    private long time;
    public MyTimeTask(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }
    public long getTime(){
        return time;
    }
    public void run(){
        runnable.run();
    }


    @Override
    public int compareTo(MyTimeTask o) {
        return   (int)(this.time-o.time);
    }
}
class MyTimer{
    PriorityQueue<MyTimeTask> queue=new PriorityQueue<>();
    Object locker =new Object();

    public void schedule(Runnable runnable,long delay){
        synchronized (locker){
        queue.offer(new MyTimeTask(runnable,delay));
        locker.notify();
    }

    }
    public MyTimer(int n){
        for (int i = 0; i < n; i++) {
            Thread t=new Thread(()->{
                while(true){
                   synchronized (locker){
                       if(queue.size()==0){
                           try {
                               locker.wait();
                           } catch (InterruptedException e) {
                               e.printStackTrace();
                           }
                       }
                        MyTimeTask myTimeTask=queue.peek();
                        long curTime=System.currentTimeMillis();
                        if(curTime>= myTimeTask.getTime()){
                            myTimeTask.run();
                            queue.poll();
                        }else{
                            try {
                                locker.wait(myTimeTask.getTime()-curTime);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                    }

                }
            });
            t.start();

        }
    }
}
public class Demo2 {
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer(10);
      myTimer.schedule(new Runnable() {
          @Override
          public void run() {
              System.out.println("hello 5000");
          }
      },5000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 7000");
            }
        },7000);

    }
}
